package org.cadet.client.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.cadet.client.bean.BeanThought;
import org.cadet.client.model.ThoughtManagement;
import org.cadet.client.model.UserManagement;

/**
 * @author Nagmani
 *
 */

public class AddThought extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AddThought() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		boolean status=false;
		String error="";
		PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        BeanThought objThought = new BeanThought();
        ThoughtManagement objThoughtManagement = new ThoughtManagement();
        try{
        	String thoughtTitle = request.getParameter("thoughtTitle").toString();
            String thoughtContent = request.getParameter("thoughtContent").toString();
            int thoughtAuthor = new UserManagement().getUserIdByName((String)(session.getAttribute("user")));
            objThought.setAuthorId(thoughtAuthor);
            objThought.setThoughtTitle(thoughtTitle);
            objThought.setThoughtContent(thoughtContent);
            try{
            	objThoughtManagement.addThought(objThought);
                status = true;
            }
            catch(Exception e){
            	error+="Databade error: " + e.getMessage();
                status = false;
            }
        }catch(Exception e){
        	error+="Outsider catch block: " + e.getMessage();
        	status=false;
        }
        if(status){
        	out.print("Thought Posted");
            request.setAttribute("status", "Done");
        }
        else{
        	out.print("Thought Not Posted" + error);
        	request.setAttribute("status", "Fail");
        }
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
